package cn.caplike.demo.rabbitmq.api.listener.returnlisterner;

import cn.caplike.demo.rabbitmq.api.Application;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Description: 用于处理一些不可路由的消息.<br>
 * Details: 消息生产者通过指定一个 Exchange 和 RoutingKey, 把消息送达到某一个队列中去, 然后消费者监听队列进行消费.<br>
 * 但是在某些情况下, 如果在发送消息的时候, 当前的 exchange 不存在或者指定的 routingKey 路由不到, 这个时候需要监听这种不可达的消息, 就要使用 return listener
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-02-19 12:18
 */
public class Producer {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Application.RABBITMQ_HOST);
        connectionFactory.setPort(Application.RABBITMQ_PORT);
        connectionFactory.setVirtualHost("/");

        // 通过链接工厂创建连接
        Connection connection = connectionFactory.newConnection();

        // 通过连接创建一个 Channel
        Channel channel = connection.createChannel();

        final String exchangeName = "test_return_exchange";
        // final String routingKey = "return.save";
        // 模拟错误的 routingKey
        final String routingKeyErr = "abd.save";

        // 发送消息
        final String msg = "Hello RabbitMQ Send return message!";
        // [!] mandatory: true 监听器会接收到路由不可达的消息; false broker 会自动删除该消息
        channel.basicPublish(exchangeName, routingKeyErr, true, null, msg.getBytes());

        // 添加一个监听
        channel.addReturnListener((replyCode, replyText, exchange, routingKey, properties, body) -> {
            System.err.println("[*] handle return ...");
            System.err.println(replyCode + " " + replyText);
        });

    }
}
